import { Form, Card, Button, Divider, Popconfirm, message } from 'antd';
import React, { Component, Fragment } from 'react';
import { FormComponentProps } from 'antd/es/form';
import { Dispatch } from 'redux';
import { StateType } from './model';
import { TableListItem, TableListPagination, TableListParams, FormItem } from './data.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './style.less';
import StandardTable, { StandardTableColumnProps } from '@/components/StandardTable';
import { SorterResult } from 'antd/es/table';
import { connect } from 'dva';
import Constants from '../creditInsurance/utils/Constants';
import moment from 'moment';
import CreditInsuranceForm from './components/CreditInsuranceForm';
import router from 'umi/router';

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  creditInsurance: StateType;
}

interface TableListState {
  modalVisible: boolean;
  selectedRows: TableListItem[];
  formValues: Partial<FormItem>;
  disabled: boolean;
}

// const getValue = (obj: { [x: string]: string[] }) =>
//   Object.keys(obj)
//     .map(key => obj[key])
//     .join(',');

@connect(
  ({
    creditInsurance,
    loading,
    global,
  }: {
    creditInsurance: StateType;
    global: StateType;
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    creditInsurance,
    global,
    loading: loading.models.creditInsurance,
  }),
)
class TableList extends Component<TableListProps, TableListState> {

  state: TableListState = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    disabled: false
  };

  columns: StandardTableColumnProps[] = [
    {
      title: '申请单号',
      dataIndex: 'id',
      render: (val: string) => <span>{`ZBT-WS-INSURANCE-CREDIT-${val}`}</span>,
    },
    {
      title: '买家名称',
      dataIndex: 'buyer',
    },
    {
      title: '联系人',
      dataIndex: 'linkman',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '电话',
      dataIndex: 'phone',
    },
    {
      title: '付款方式',
      dataIndex: 'paymentType',
    },
    {
      title: '所需信用额度',
      dataIndex: 'creditLimit',
    },
    {
      title: '保费',
      dataIndex: 'premium',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (val: string) => <span>{Constants.STATUS[val]}</span>
    },
    {
      title: '申请时间',
      dataIndex: 'createtime',
      render: (val: string) => <span>{moment(val).format('YYYY-MM-DD')}</span>,
    },
    {
      title: '操作',
      render: (text, record) => ( 
        <Fragment>
          <span style={{ display: record.status === '1' ? 'inline-bloc' : 'none' }}>
          <a target="_blank" onClick={this.handleGetGoods.bind(this, record)}>付款</a>
            <Divider type="vertical" />
          </span>
          <span style={{display: record.status === '3' ? 'inline-bloc' : 'none'}}>
            <Popconfirm
              onConfirm={this.doInsurance.bind(this, record)}
              okText="是"
              cancelText="否"
              placement="leftTop"
              title={'是否确认投保?'}

            >
              <a href="#">投保</a>
            </Popconfirm>
            <Divider type="vertical" />
          </span>
          <a onClick={() => this.handleUpdateModalVisible(true, record, true)}>详情</a>
        </Fragment>
      ),
    },
  ];

  handleGetGoods = record => {
    this.props.dispatch({
      type: 'creditInsurance/getGoods',
      payload: {
        type: '5',
        page: 1,
        size: 10,
        onSuccess: data => {
          if (data) {
            router.push('/pay/payConfirm?goodsId=' + data[0].id + '&entityid=' + record.id + '&bussinesstype=' + '5');
          }
        },
      },
    });
  };

  doInsurance = (record?: Object) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'creditInsurance/update',
      payload: {
        id: record.id,
        onSuccess: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'creditInsurance/fetch',
            payload: {
              page: Constants.DEFAULT_PAGE.page,
              size: Constants.DEFAULT_PAGE.size
            }
          });
        }
      }
    });
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'creditInsurance/fetch',
      payload: {
        page: Constants.DEFAULT_PAGE.page,
        size: Constants.DEFAULT_PAGE.size
      }
    });
  }

  handleStandardTableChange = (pagination: Partial<TableListPagination>, filtersArg: Record<keyof TableListItem, string[]>, sorter: SorterResult<TableListItem>) => {
    const { dispatch } = this.props;

    // const filters = Object.keys(filtersArg).reduce((obj, key) => {
    //   const newObj = { ...obj };
    //   newObj[key] = getValue(filtersArg[key]);
    //   return newObj;
    // }, {});

    const params: Partial<TableListParams> = {
      page: pagination.current,
      size: pagination.pageSize
    };
    // if (sorter.field) {
    //   params.sorter = `${sorter.field}_${sorter.order}`;
    // }

    dispatch({
      type: 'creditInsurance/fetch',
      payload: params,
    });
  };

  handleUpdateModalVisible = (flag?: boolean, record?: Partial<TableListItem>, disabled?: boolean) => {
    this.setState({ modalVisible: !!flag, formValues: {}, disabled: !!disabled });
    if (record) {
      const { dispatch } = this.props;
      dispatch({
        type: 'creditInsurance/get', payload: {
          id: record.id,
          onSuccess: (data?: Partial<FormItem>) => {
            this.setState({ formValues: data || {}, disabled: !!disabled });
          }
        }
      });
    }
  };

  handleSave = (fields: FormItem) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'creditInsurance/add',
      payload: {
        ...fields,
        onSuccess: () => {
          this.handleUpdateModalVisible();
          const { dispatch } = this.props;
          dispatch({
            type: 'creditInsurance/fetch',
            payload: {
              page: Constants.DEFAULT_PAGE.page,
              size: Constants.DEFAULT_PAGE.size
            }
          });
        }
      },
    });
  };

  render() {

    const { creditInsurance: { data }, loading } = this.props;

    const { selectedRows, modalVisible, formValues, disabled } = this.state;

    const methods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleSave: this.handleSave,
    };

    return (
      <PageHeaderWrapper content={<span>
        1、投保出口信用险需要先评估买家资质，若您已经完成评估，可以直接选择“投保”;<br />
        2、您提交成功后，评估买家资质需要10个工作日左右,评估买家的费用根据不同国家和地区存在差异;<br />
        3、每次出货都需要操作投保，所以请务必准确提供货物信息;<br />
        4、洲博通已经购买大保单，无需您再次购买，可以直接投保；确认投保后即代表您同意通过洲博通完成货物出口。
      </span>}>
        <Card bordered={false}>
          {
            modalVisible ?
              <CreditInsuranceForm
                {...methods}
                data={formValues}
                disabled={disabled}
              /> :
              <div className={styles.tableList}>
                <div className={styles.tableListOperator}>
                  <Button icon="plus" type="primary" onClick={() => this.handleUpdateModalVisible(true)}>立即申请</Button>
                </div>
                <StandardTable
                  selectedRows={selectedRows}
                  loading={loading}
                  data={data}
                  columns={this.columns}
                  onSelectRow={this.handleSelectRows}
                  onChange={this.handleStandardTableChange}
                />
              </div>
          }

        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
